package com.qianmi.xsite.render.util;

import com.qianmi.xsite.render.domain.XSitePageResponse;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *************************************************************************************
 * 请求发送工具类
 *
 * @author yujialin
 */
public final class HttpRequester {

    private static Logger logger = LoggerFactory.getLogger(HttpRequester.class);

    private static final int DEFAULT_CONNECTIONTIMEOUT = 10000;
    private static final int DEFAULT_READTIMEOUT = 10000;
    private static final int DEFAULT_TIMEOUT = 10000;
    private static final int STATUSCODE = 200;

    private HttpRequester() {

    }

    /**
     * ******************************************
     * 以post方式发送请求
     *
     * @param url
     * @param paramMap
     * @param encode
     * @return
     */
    public static XSitePageResponse post(String url, Map<String, String> paramMap, String encode) {

        return post(url, paramMap, encode, DEFAULT_CONNECTIONTIMEOUT, DEFAULT_READTIMEOUT);
    }

    /**
     * ********************************
     *
     * @param url
     * @param paramsMap
     * @return
     */
    @SuppressWarnings("deprecation")
    public static XSitePageResponse post(String url, Map<String, String> paramsMap) {

        return post(url, paramsMap, HTTP.UTF_8, DEFAULT_CONNECTIONTIMEOUT, DEFAULT_READTIMEOUT);
    }

    /**
     * ********************************
     *
     * @param url
     * @param paramMap
     * @param headersMap
     * @return
     */
    @SuppressWarnings("deprecation")
    public static XSitePageResponse post(String url, Map<String, String> paramMap, Map<String, String> headersMap) {

        return post(url, paramMap, HTTP.UTF_8, DEFAULT_CONNECTIONTIMEOUT, DEFAULT_READTIMEOUT, headersMap);
    }

    /**
     * **********************
     *
     * @param url
     * @return
     */
    @SuppressWarnings("deprecation")
    public static XSitePageResponse post(String url) {

        return post(url, null, HTTP.UTF_8, DEFAULT_CONNECTIONTIMEOUT, DEFAULT_READTIMEOUT);
    }

    /**
     * *******************************
     *
     * @param url
     * @param encode
     * @return
     */
    public static XSitePageResponse post(String url, String encode) {

        return post(url, null, encode, DEFAULT_CONNECTIONTIMEOUT, DEFAULT_READTIMEOUT);
    }

    /**
     * ********************************
     *
     * @param url
     * @param connectiontimeout
     * @param readtimeout
     * @return
     */
    @SuppressWarnings("deprecation")
    public static XSitePageResponse post(String url, int connectiontimeout, int readtimeout) {

        return post(url, null, HTTP.UTF_8, connectiontimeout, readtimeout);
    }

    /**
     * *********************************
     *
     * @param url
     * @param encode
     * @param connectiontimeout
     * @param readtimeout
     * @return
     */
    public static XSitePageResponse post(String url, String encode, int connectiontimeout, int readtimeout) {

        return post(url, null, encode, connectiontimeout, readtimeout);
    }

    /**
     * *****************************************
     *
     * @param url
     * @param paramsMap
     * @param encode
     * @param connectiontimeout
     * @param readtimeout
     * @return
     */
    public static XSitePageResponse post(String url, Map<String, String> paramsMap, String encode, int connectiontimeout,
                              int readtimeout) {
        return post(url, paramsMap, encode, connectiontimeout, readtimeout, null);
    }


    private static String[] responseHeaders =  new String[]{
            "XSite-page-index-pageType",//首页页面类型编码
            "XSite-page-index-pageCode",//生效首页页面code
            "XSite-page-index-pageStyle",//首页风格
            "XSite-page-index-tplCode",//首页模板编码
            "XSite-env-code",//所取render项目所在环境信息 test gray prod
            "XSite-Content-Encoding",//页面是否编码了..
    };


    /**
     * *****************************************
     *
     * @param url
     * @param paramsMap
     * @param encode
     * @param connectiontimeout
     * @param readtimeout
     * @param headersMap
     * @return
     */
    public static XSitePageResponse post(String url, Map<String, String> paramsMap, String encode, int connectiontimeout,
                              int readtimeout, Map<String, String> headersMap) {
        String resultStr = null;
        Map<String,String> responseHeaders =new HashMap<>();

        HttpClient httpclient = null;
        try {
            HttpPost httppost = new HttpPost(url);
            if (paramsMap != null) {
                // 用于存放请求参数
                List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
                httppost.setEntity(entity);
            }
            httppost.setHeader("Connection", "close");
            if (headersMap != null){
                for (Map.Entry<String, String> header: headersMap.entrySet()
                     ) {
                    httppost.setHeader(header.getKey(), header.getValue());
                }
            }
            httpclient = new DefaultHttpClient();
            HttpParams params = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, connectiontimeout);
            HttpConnectionParams.setSoTimeout(params, readtimeout);
            // 发送post
            HttpResponse httpResponse = httpclient.execute(httppost);
            // 请求
            if (httpResponse.getStatusLine().getStatusCode() == STATUSCODE) {

                for(int i  = 0 ,iLen =HttpRequester.responseHeaders.length;i<iLen;i++){
                    String headerName =HttpRequester.responseHeaders[i];
                    Header  header =  httpResponse.getFirstHeader(headerName);
                    if(header !=null){
                        responseHeaders.put(headerName, header.getValue());
                    }
                }

                Header[]  header =   httpResponse.getHeaders("XSite-Content-Encoding");
                resultStr = EntityUtils.toString(httpResponse.getEntity(), encode);
                //如果是gzip压缩了, 那么进行解压
                if(header !=null && header.length ==1 && header[0].getValue().equalsIgnoreCase("gzip")){
                    resultStr=  ZlibUtil.unGzip(resultStr);
                }
                if (resultStr != null) {
                    resultStr = resultStr.trim();
                }
                EntityUtils.consume(httpResponse.getEntity());
            } else {
                resultStr = httpResponse.getStatusLine().toString();
                logger.error("请求失败，返回：" + resultStr);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (httpclient != null) {
                httpclient.getConnectionManager().shutdown();
            }
        }

        return  new XSitePageResponse(resultStr,responseHeaders);
    }

    /**
     * *************************
     *
     * @param url
     * @return
     * @Description: get方法
     */
    public static String get(String url) {
        return get(url, HTTP.UTF_8, null);
    }

    /**
     * *************************
     *
     * @param url
     * @param encode
     * @return
     * @Description: get方法
     * @author yujialin
     * @date May 31, 2011 3:47:39 PM
     */
    public static String get(String url, String encode) {
        return get(url, encode, null);
    }

    /**
     * *************************
     *
     * @param url
     * @param headersMap
     * @return
     * @Description: get方法
     */
    public static String get(String url, Map<String, String> headersMap) {
        return get(url, HTTP.UTF_8, headersMap);
    }

    /**
     * *************************
     *
     * @param url
     * @param encode
     * @param headersMap
     * @return
     * @Description: get方法
     * @author yujialin
     * @date May 31, 2011 3:47:39 PM
     */
    public static String get(String url, String encode, Map<String, String> headersMap) {
        String resultStr = null;

        HttpClient httpclient = null;
        try {
            HttpGet httpget = new HttpGet(url);
            httpclient = new DefaultHttpClient();
            HttpParams params = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, DEFAULT_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, DEFAULT_TIMEOUT);
            if (headersMap != null){
                for (Map.Entry<String, String> header: headersMap.entrySet()
                        ) {
                    httpget.setHeader(header.getKey(), header.getValue());
                }
            }
            // 发送post 请求
            HttpResponse httpResponse = httpclient.execute(httpget);
            if (httpResponse.getStatusLine().getStatusCode() == STATUSCODE) {
                Header[]  header =   httpResponse.getHeaders("XSite-Content-Encoding");
                resultStr = EntityUtils.toString(httpResponse.getEntity(), encode);
                //如果是gzip压缩了, 那么进行解压
                if(header !=null && header.length ==1 && header[0].getValue().equalsIgnoreCase("gzip")){
                    resultStr=  ZlibUtil.unGzip(resultStr);
                }

                if (resultStr != null) {
                    resultStr = resultStr.trim();
                }
                EntityUtils.consume(httpResponse.getEntity());
            } else {
                resultStr = httpResponse.getStatusLine().toString();
                logger.error("请求失败，返回：" + resultStr);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (httpclient != null) {
                httpclient.getConnectionManager().shutdown();
            }
        }

        return resultStr;
    }
    
    /**
     * 
     * 此处为功能说明
     * 
     * @author 唐坤[0F935] 
     * @date 2014-4-8 下午3:47:34
     * @param url
     * @param encode
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String postEntity(String url, HttpEntity param, String encode) throws Exception {
        String resultStr = null;
        HttpClient httpclient = null;
        try {
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(param);
            httpclient = new DefaultHttpClient();
            HttpResponse httpResponse = httpclient.execute(httppost);
            if (httpResponse.getStatusLine().getStatusCode() == STATUSCODE) {
                resultStr = EntityUtils.toString(httpResponse.getEntity(), encode);
                if (resultStr != null) {
                    resultStr = resultStr.trim();
                }
                EntityUtils.consume(httpResponse.getEntity());
            } else {
                resultStr = httpResponse.getStatusLine().toString();
                logger.error("请求失败，返回：" + resultStr);
            }
        }finally {
            if (httpclient != null) {
                httpclient.getConnectionManager().shutdown();
            }
        }

        return resultStr;
    }
}
